package net.javalib.gvmax.post.server.util;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;


public class NetUtil {

	public static String doGet(String url) throws IOException {
		URL u = new URL(url);
		return IOUtil.toString(u.openStream(),"utf8");
	}

	public static String doGet(String url, String charset) throws IOException {
		URL u = new URL(url);
		return IOUtil.toString(u.openStream(),charset);
	}

	public static String doPost(String url, Map<String, String> params) throws IOException {
		return doPost(url, params, null, "utf8");
	}	
	
	public static String doPost(String url, Map<String, String> params, String charset) throws IOException {
		return doPost(url, params, null, charset);
	}
	
	public static String doPost(String url, Map<String, String> params, Map<String,String> reqProperties) throws IOException {
		return doPost(url,params,reqProperties,"utf8");
	}
	
	public static String doPost(String url, Map<String, String> params, Map<String,String> reqProperties, String charset) throws IOException {
		String paramsStr = "";
		Iterator<String> paramNames = params.keySet().iterator();
		if (paramNames.hasNext()) {
			String paramName = paramNames.next();
			paramsStr = paramName + "=" + URLEncoder.encode(params.get(paramName),"utf8");
		}
		while (paramNames.hasNext()) {
			String paramName = paramNames.next();
			paramsStr += "&"+paramName + "=" + URLEncoder.encode(params.get(paramName),"utf8");
		}
		byte[] postData = paramsStr.getBytes("utf8");
		
		
		URL u = new URL(url);

		HttpURLConnection conn = (HttpURLConnection) u.openConnection();
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
		if (reqProperties != null) {
			for (String rpName : reqProperties.keySet()) {
				conn.setRequestProperty(rpName, reqProperties.get(rpName));
			}
		}

		OutputStream out = conn.getOutputStream();
        out.write(postData);
        out.close();
		        
		return IOUtil.toString(conn.getInputStream(),charset);
	}
	
}

